<template>
  <div class="timing">
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-form :inline="true" :model="formInline" class="demo-form-inline queryFrom">
          <el-form-item label="数据库名称">
            <el-input v-model="formInline.dataModelName" clearable placeholder="请输入数据库名称" />
          </el-form-item>
          <el-form-item>
            <el-button plain @click="getUserList"><Icon type="ios-search" />查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-button type="primary" @click="addUser('add')"><Icon type="md-add" />创建数据源</el-button>
        <el-button @click="libraryTableTbSyn">库表同步</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <ykhttb width="250" ref="httbRef" :btn-is-show="btnIsShow" :table-col="tabUserList" :table-data="tableUserData"
    @getDataDetileInfo="getDataDetileInfo"
     @deleteSelectData="deleteSelectData" @refresh="getUserList" />
    <!-- 分页 -->
    <div style="text-align:right;margin-top:10px;">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :close-on-click-modal="false" :title="title" width="50%" :visible.sync="dialogTableVisible">
      <!-- 名称和路径必输 -->
      <el-form v-if="dialogTableVisible" ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" class="demo-ruleForm autoClass">
        <el-form-item label="数据库类型" prop="databaseType">
            <el-select :disabled="disFlag" @change="setdriver" v-model="ruleForm.databaseType" clearable placeholder="请选择">
              <el-option
                v-for="(item,i) in dataType"
                :key="i"
                :label="item.databaseType"
                :value="item.databaseType"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="数据源名称" prop="connectName">
          <el-input :disabled="disFlag" v-model="ruleForm['connectName']" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="描述" prop="comments">
          <el-input :disabled="disFlag" v-model="ruleForm['comments']" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="数据库名称" prop="databaseName">
          <el-input :disabled="disFlag" v-model="ruleForm['databaseName']" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="JDBC驱动" prop="driver">
          <el-input disabled="true"  v-model="ruleForm['driver']" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="JDBC URL" prop="url">
          <el-input :disabled="disFlag" v-model="ruleForm['url']" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="查询所有表名的SQL" prop="tableSql">
          <el-input :disabled="disFlag" v-model="ruleForm['tableSql']" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input :disabled="disFlag" v-model="ruleForm['username']" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input :disabled="disFlag" v-model="ruleForm['password']" clearable placeholder="" />
        </el-form-item>
      </el-form>
      <div style="text-align: center;">
        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        <el-button plain @click="testFun('ruleForm')" type="primary">测试</el-button>
        <el-button @click="resetForm('return')">返回</el-button>
      </div>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" width="50%" :visible.sync="testdialogTableVisible">
      <div class="resoceDialog" >
        <div style="width:38%">
          <p>源</p>
          <el-form label-width="80px" class="demo-ruleForm">
            <el-form-item label="数据源" prop="name">
                <el-select v-model="scoreA" @change="getZtreeList(scoreA,1)" clearable placeholder="请选择">
                  <el-option
                    v-for="(item,i) in sourceList"
                    :key="i"
                    :label="item.connectName"
                    :value="item.id"
                  />
                </el-select>
            </el-form-item>
          </el-form>
          <div class="ztree">
            <p v-for="(item,index) in elradioOptionsa" :key="index"><el-radio v-model="leftRadio" :label="item">{{ item }}</el-radio></p>
          </div>
          <div class="info">
            <p>信息</p>
            <p><label for="">项目名：</label><span v-show="sysInfo1.databaseName">{{ sysInfo1.databaseName }}</span> </p>
            <p><label for="">连接类型：</label><span v-show="sysInfo1.databaseType">{{ sysInfo1.databaseType }}</span></p>
            <p><label for="">连接名：</label><span v-show="sysInfo1.connectName">{{ sysInfo1.connectName }}</span></p>
          </div>
        </div>
        <div style="width:20%;text-align: center;padding-top: 150px;">
          <img width="120" src="@/assets/images/jt.jpg" alt="">
        </div>
        <div style="width:38%;">
          <p>目标</p>
          <el-form label-width="60px" class="demo-ruleForm">
            <el-form-item label="数据源" prop="name">
                <el-select v-model="scoreB"  @change="getZtreeList(scoreB,2)" clearable placeholder="请选择">
                  <el-option
                    v-for="(item,i) in sourceList2"
                    :key="i"
                    :label="item.connectName"
                    :value="item.id"
                  />
                </el-select>
            </el-form-item>
          </el-form>
          <div class="ztree" style="margin-left:60px;">
            <p v-for="(item,index) in elradioOptionsb" :key="index">{{ item }}</p>
          </div>
          <div class="info">
            <p style="margin-left:60px;">信息</p>
            <p style="margin-left:60px;"><label for="">项目名：</label><span v-show="sysInfo2.databaseName">{{ sysInfo2.databaseName }}</span> </p>
            <p style="margin-left:60px;"><label for="">连接类型：</label><span v-show="sysInfo2.databaseType">{{ sysInfo2.databaseType }}</span></p>
            <p style="margin-left:60px;"><label for="">连接名：</label><span v-show="sysInfo2.connectName">{{ sysInfo2.connectName }}</span></p>
          </div>
        </div>
      </div>
      <div style="text-align: center;margin-top: 50px;">
        <el-button @click="closetestdialogTableVisible" type="primary">开始</el-button>
        <el-button @click="closetestdialogTableVisible('return')">返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { dataSourcepage, dataSourcesave,dataSourcesaveDataSource, dataSourcedelete,dataSourceconnect,
  dataSourcelist,dataSourcequeryAllTableName,dataSourceget,databaselist,
  dataSourcemoveTableData
} from '@/api/zt/index'
import experiment from '@/mixins/experiment'
export default {
  components: {},
  mixins: [experiment],
  data() {
    return {
      dataType:[],
      elradioOptionsa:[],
      elradioOptionsb:[],
      leftRadio:'',
      sourceList:[],
      sourceList2:[],
      scoreA:"",
      scoreB:"",
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      ruleForm2:{

      },
      testdialogTableVisible:false,
      btnIsShow: {
        operate: true,
        detile: true,
        del: true
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      title: '新增',
      rules: {
        databaseType: [
            { required: true, message: '请选择数据库类型', trigger: 'change' }
        ],
        connectName: [
            { required: true, message: '请输入数据源名称', trigger: 'change' }
        ],
        databaseName: [
            { required: true, message: '请输入数据库名称', trigger: 'change' }
        ],
        driver: [
            { required: true, message: '请输入JDBC驱动', trigger: 'change' }
        ],
        url: [
            { required: true, message: '请输入JDBC URL', trigger: 'change' }
        ],
        tableSql: [
            { required: true, message: '请输入查询所有表名的SQL', trigger: 'change' }
        ],
        username: [
            { required: true, message: '请输入用户名', trigger: 'change' }
        ],
        password: [
            { required: true, message: '请输入密码', trigger: 'change' }
        ] 
      },
      dialogTableVisible: false,
      ruleForm: {
        "comments": "",
        "connectName": "",
        "createTime": "",
        "dataSourceType": "",
        "databaseName": "",
        "databaseType": "",
        "driver": "",
        "id": 0,
        "password": "",
        "spare1": "",
        "spare2": "",
        "tableSql": "",
        "updateTime": "",
        "url": "",
        "username": ""
      },
      userId: '',
      formInline: {
        'dataModelName': '',
        'dataModelTypeId': ''
      },
      addParms: [],
      addParms2: [],
      tableUserData: [],
      sysInfo1:{},
      sysInfo2:{},
      fullscreenLoading:false,
      tabUserList: [
        {
          key: 'connectName',
          title: '数据源名称'
        },
        {
          key: 'databaseType',
          title: '数据库类型'
        },
        {
          key: 'driver',
          title: '驱动'
        },
        {
          key: 'dataSourceType',
          title: '数据库来源'
        }
        // {
        //   key: 'createTime',
        //   title: '状态'
        // }
      ],
      total: 0,
      size: 10,
      noChangeList:[],
      changeList:[],
      page: 1
    }
  },
  created() {

  },
  mounted() {
    this.$nextTick(() => {
      this.getUserList()

      dataSourcelist({}).then(res=>{
        this.sourceList = JSON.parse(JSON.stringify(res.data))
        this.sourceList2 = JSON.parse(JSON.stringify(res.data))
        this.noChangeList = JSON.parse(JSON.stringify(res.data))
        this.changeList = JSON.parse(JSON.stringify(res.data))
      })
      databaselist({}).then(res=>{
        this.dataType = res.data
      })
    })
  },
  methods: {
    setdriver(){
      this.dataType.forEach((item,index)=>{
        if(this.ruleForm.databaseType == item.databaseType){
          this.ruleForm['driver'] = item.driver
        } 
      })
    },
    filterSelectDataList(i){
      this.sourceList2 = JSON.parse(JSON.stringify(this.noChangeList))
      if(i==1){
        if(this.scoreA){
          this.noChangeList.forEach((item,index)=>{
            if(item.id==this.scoreA){
              this.sourceList2.splice(index,1)
            }
          })
          this.scoreB = ''
          this.elradioOptionsb = []
          this.sysInfo2 = {}
        }else{
          this.elradioOptionsa = []
          this.sysInfo1 = {}
        }
      }else{
        if(!this.scoreB){
          this.elradioOptionsb = []
          this.sysInfo2 = {}
        }
      }
    },
    getZtreeList(v,i){
       // 过滤下拉框数据
       this.filterSelectDataList(i)
      if(!v){
        return 
      }
      dataSourcequeryAllTableName({dataSourceId:v}).then(res=>{
        if(i==1){
          this.elradioOptionsa = res.data
        }else{
          this.elradioOptionsb = res.data
        }
      })
      dataSourceget({id:v}).then(res=>{
        if(i==1){
          this.sysInfo1 = res.data
        }else{
          this.sysInfo2 = res.data
        }
      })
     
    },

    closetestdialogTableVisible(v){
      if(v!='return'){
        if(this.scoreA==''||this.scoreB==''){
          this.$message.error('请先选择数据源')
          return 
        }
        if(this.leftRadio==''){
          this.$message.error('请先选择表名')
          return 
        }
      this.fullscreenLoading = true;
        dataSourcemoveTableData(
          {
            dataSourceId:this.scoreA,
            tableName:this.leftRadio,
            targetId:this.scoreB
          }
        ).then(res=>{
          if(res.code==200){
            this.$message.success('复制成功')
            dataSourcequeryAllTableName({dataSourceId:this.scoreB}).then(res=>{
              this.elradioOptionsb = res.data
            })
          }else{
            this.$message.error('复制失败')
          }
          this.fullscreenLoading = false;
        })
        setTimeout(()=>{
        this.fullscreenLoading = false;
      },10000)
      }else{
        this.sourceList = []
        this.elradioOptionsa = []
        this.elradioOptionsb = []
        this.testdialogTableVisible = false
      }
    },
    libraryTableTbSyn(){
      this.testdialogTableVisible = true
    },
    deleteSelectData(v) {
      const ids = [v.id] 
      dataSourcedelete(ids).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    handleNodeClick(data) {
      console.log(data)
    },
    testFun(v){
        this.$refs[v].validate((valid) => {
          if (valid) {
            dataSourceconnect(this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success('测试成功！')
              } else {
                this.errorDialog(res.msg)
              }
            })
          } else {
            return false;
          }
        });
    },
    commitFromData() {
      dataSourcesaveDataSource(this.ruleForm).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    handleSizeChange(v) {
      this.page = 1
      this.size = v
      this.getUserList()
    },
    handleCurrentChange(v) {
      this.page = v
      this.getUserList()
    },

    // 获取用户列表
    getUserList() {
      this.dialogTableVisible = false
      this.$refs.httbRef.isShowLoading(true)

      dataSourcepage({
        'pageIndex': this.page,
        'or_orderby_createTime':'dsc',
        'sk_like_databaseName': this.formInline.dataModelName,
        'pageSize': this.size
      }).then(res => {
        this.tableUserData = res.data.records
        this.total = res.data.total
      this.$refs.httbRef.isShowLoading(false)

      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "~@/assets/styles/auto.scss";
      .info{
        margin-top: 20px;
      }
      .info>p{
        padding:4px 0;
        margin-left:80px;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
      }
      .info>p:nth-child(1){
        color: #474747;
        font-weight: bold;
        background: #f1f4f7;
        padding-left: 0px;
      }
      .info>p>label{
        display: inline-block;
        width:35%;
      }
      .info>p>span{
        color:#494949;padding: 2px 4px;
        border-radius: 2px;font-size: 12px;
        background: #f0f0f0;
      }
    .ztree {
        margin-left:80px;
        border:1px solid #efefef;
        padding: 4px;
        border-radius: 2px;
        min-height: 270px;
        height: 300px;
        overflow-y: scroll;
    }
    .resoceDialog{
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: space-between;
    }
    .resoceDialog>div>p{
      color: #464646;
      padding: 10px 0;
      font-weight: bold;
      // background: #f1f4f7;
      margin-left:26px;
      padding-left:0px;
      margin-bottom: 5px;
      text-align: right;
    }
      >>>.jsoneditor-poweredBy {
        display: none !important;
      }

      .addPs{
        display: flex;
        flex-direction: row;
        margin-bottom: 10px;
        >div{
          width:50%
        }
        span{
          display: inline-block;
          width: 10%;
        }
      }
      .autoClass{
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
      }
      .autoClass .el-form-item{
        width:50%;
      }
      .addcs{
        display: flex;
        flex-direction: row;
        margin-bottom: 10px;
      }
      .addcs2 .el-select {
        display: inline-block;
        width: 240px;
      }
      .autoInput{
        display: inline-block;
        width: 70%;
      }
      .infoTitle{
        border-bottom:1px solid #e5e5e5;
        margin-bottom: 30px;
        position: relative;
      }
      .infoTitle>span{
        position: absolute;
        left: 20px;
        background: #fff;
        width:80px;
        top:-15px;
        height:30px;
        text-align: center;
        line-height: 30px;
      }
        .el-select{
           width:100%;
        }
        .timing{
          background:#fff;
          padding:20px;
        }
      </style>
